<template>
    <div class="content">
        <MonitorSearch @handle-btn="handleBtn" ref="risk-search" />
        <el-row>
            <div class="report">
                <RiskTableP
                    ref="risk-table"
                    :tableConfig="tableConfigEntry"
                    :tableData="tableDataEntry"
                    :column="tableColumnsEntry"
                    :paging="pagingEntry"
                    :searchParams="filterParams"
                    @page-change="getTableDataEntry"
                    @cell-click="handleCellClick"
                    highlight-hover-row
                    highlight-current-row
                    :key="tableKey + 'entry'"
                >
                    <template #entryName="scope">
                        <span @click.stop="handleRowClick(scope.row)" class="text-hover">
                            {{ scope.row.entryName }}
                        </span>
                    </template>
                    <template #thresholdType="scope">
                        <StatusTag :code="scope.row.thresholdType"></StatusTag>
                    </template>
                    <template #fundNames="scope">
                        <el-popover
                            v-if="getObjectLength(scope.row.fundNames) && getObjectLength(scope.row.fundNames) > 1"
                            placement="right"
                            trigger="hover"
                            :visible-arrow="false"
                        >
                            <div slot v-for="(ele, index) in scope.row.fundNames" :key="index">
                                {{ ele }}
                            </div>
                            <el-tag slot="reference" style="background: #f1e9e2; color: #bf9181" size="small">
                                {{ getObjectLength(scope.row.fundNames) + '个产品' }}
                            </el-tag>
                        </el-popover>
                        <span v-else-if="getObjectLength(scope.row.fundNames)" v-for="(ele, index) in scope.row.fundNames" :key="index">{{
                            ele
                        }}</span>
                        <span v-else>无</span>
                    </template>
                </RiskTableP>
            </div>
            <div style="margin-left: 10px" class="report">
                <RiskTableP
                    :tableConfig="tableConfigEntryDetail"
                    :tableData="tableDataEntryDetail"
                    :column="tableColumnsEntryDetail"
                    :paging="pagingEntryDetail"
                    :searchParams="filterParamsEntryDetail"
                    @page-change="getTableDataEntryDetail"
                    :key="tableKey + 'fund'"
                >
                    <template #calculateValue="scope">
                        <span
                            :style="{
                                textDecoration: 'underline',
                                textDecorationColor: ThresholadEntryColor[scope.row.thresholdType],
                                color: ThresholadEntryColor[scope.row.thresholdType],
                                cursor: 'pointer',
                            }"
                            @click="openEntryResultDetail(scope.row)"
                        >
                            {{ numberFormat(scope.row.calculateValue) }}
                        </span>
                    </template>

                    <template #fundCode="scope">
                        <!-- <el-popover
                            v-if="scope.row.fundCodes && scope.row.fundCodes.length > 1"
                            placement="right"
                            trigger="hover"
                            :visible-arrow="false"
                        >
                            <div style="padding: 0 10px 10px 0" slot v-for="(ele, index) in scope.row.fundCodes" :key="index">
                                {{ ele }}
                            </div>
                            <el-tag slot="reference" style="background: #f1e9e2; color: #bf9181" size="small">
                                {{ getObjectLength(scope.row.fundCodes) + '个产品' }}
                            </el-tag>
                        </el-popover> -->
                        <span v-if="scope.row.fundCodes && scope.row.fundCodes.length > 1"> 无 </span>
                        <!-- <span v-else-if="scope.row.fundCodes && scope.row.fundCodes.length === 1">无</span> -->
                        <span v-else>{{ scope.row.fundCode }}</span>
                    </template>

                    <template #fundNameSt="scope">
                        <!-- <el-popover
                            v-if="scope.row.fundNames && scope.row.fundNames.length > 1"
                            placement="right"
                            trigger="hover"
                            :visible-arrow="false"
                        >
                            <div style="padding: 0 10px 10px 0" slot v-for="(ele, index) in scope.row.fundNames" :key="index">
                                {{ ele }}
                            </div>
                            <el-tag slot="reference" style="background: #f1e9e2; color: #bf9181" size="small">
                                {{ getObjectLength(scope.row.fundNames) + '个产品' }}
                            </el-tag>
                        </el-popover> -->
                        <span v-if="scope.row.fundNames && scope.row.fundNames.length > 1">无</span>
                        <!-- <span v-else-if="scope.row.fundNames && scope.row.fundNames.length === 1">无</span> -->
                        <span v-else>{{ scope.row.fundNameSt }}</span>
                    </template>

                    <template #thresholdType="scope">
                        <StatusTag :code="scope.row.thresholdType"></StatusTag>
                    </template>
                    <template #stockCode="scope">
                        <el-tooltip placement="top-start" :disabled="(!scope.row.stockInfos) || !(scope.row.stockInfos.length > 0)">
                            <ul slot="content" style="min-height: 18px; max-height: 200px; overflow: auto">
                                <li :key="item" v-for="item in scope.row.stockInfos">
                                    {{ item.dictKey + '(' + item.dictKeyName + ')' }}
                                </li>
                            </ul>
                            <span>{{ setStockCode(scope.row) }}</span>
                        </el-tooltip>
                    </template>
                    <!-- <template #stockCode="scope">
                        <el-popover
                            v-if="getObjectLength(scope.row.stockCode) && getObjectLength(scope.row.stockCode) > 1"
                            placement="right"
                            trigger="hover"
                            :visible-arrow="false"
                        >
                            <div slot v-for="(ele, index) in scope.row.stockCode" :key="index">
                                {{ ele }}
                            </div>
                            <el-tag slot="reference" size="small">{{ getObjectLength(scope.row.stockCode) + '个证券' }}</el-tag>
                        </el-popover>
                        <span v-else-if="getObjectLength(scope.row.stockCode)" v-for="(ele, index) in scope.row.stockCode" :key="index">{{
                            ele
                        }}</span>
                        <span v-else>无</span>
                    </template> -->
                </RiskTableP>
            </div>
        </el-row>
    </div>
</template>
<script lang="ts">
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { ColumnVO, PageVO, TableConfigVO } from '@/common/vo';
import { numberFormat } from '@/utils/tools';
import { Component, Vue } from 'vue-property-decorator';
import MonitorSearch from './monitor-search.vue';
import { getEntryResult, queryDetail } from './api/item-real-time-monitoring';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import RiskEmitter from '@/common/mixis/risk-emitter.vue';
import { mixins } from 'vue-class-component';
@Component({ name: 'FundResult', components: { RiskTableP, MonitorSearch, StatusTag } })
export default class FundResult extends mixins(RiskEmitter) {
    numberFormat = numberFormat;
    tableConfigEntry: TableConfigVO = {
        rowKey: 'entryCode', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableDataEntry: any[] = [
        {
            entryCode: '80001X',
            entryName: '【现金管理产品运作管理指引】全部产品和货币基金投资同一商业银行的银行存款及其发行的同业存单与债券、已该金融机构为交易对手的逆',
            fundCode: '001',
            fundNames: ['招商证券产品1', '2招商证券产品1'],
            thresholdType: '0',
        },
        {
            entryCode: '80002X',
            entryName: '【现金管理产品运作管理指引】全部产品和货币基金投资同一商业银行的银行存款及其发行的同业存单与债券、已该金融机构为交易对手的逆',
            fundCode: '002',
            fundNames: ['招商证券产品1'],
            thresholdType: '2',
        },
        {
            entryCode: '80003X',
            entryName: '【现金管理产品运作管理指引】全部产品和货币基金投资同一商业银行的银行存款及其发行的同业存单与债券、已该金融机构为交易对手的逆',
            fundCode: '003',
            fundNames: ['招商证券产品1'],
            thresholdType: '3',
        },
        {
            entryCode: '80003X',
            entryName: '【现金管理产品运作管理指引】全部产品和货币基金投资同一商业银行的银行存款及其发行的同业存单与债券、已该金融机构为交易对手的逆',
            fundCode: '003',
            fundNames: ['招商证券产品1'],
            thresholdType: '4',
        },
    ];
    tableColumnsEntry: ColumnVO[] = [
        {
            title: '条目编号',
            field: 'entryCode',
            filterType: 'search',
            filters: [{ data: '' }],
            width: '120',
        },
        {
            title: '条目名称',
            field: 'entryName',
            filterType: 'search',
            filters: [{ data: '' }],
            minWidth: '180',
        },
        {
            title: '触警状态',
            field: 'thresholdType',
            width: '120',
        },
        {
            title: '超限产品',
            field: 'fundNames',
            width: '120',
        },
    ];
    pagingEntry: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    // 条目明细-展示条目相应的产品
    tableConfigEntryDetail: TableConfigVO = {
        rowKey: 'resultId', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableDataEntryDetail: any[] = [];
    tableColumnsEntryDetail = [
        {
            title: '产品编码',
            field: 'fundCode',
            filterType: 'search',
            filters: [{ data: '' }],
            width: '120',
        },
        {
            title: '产品名称',
            field: 'fundNameSt',
            filterType: 'search',
            filters: [{ data: '' }],
            minWidth: '160',
        },
        {
            title: '实际值',
            field: 'calculateValue',
            width: '100',
        },
        {
            title: '触发证券代码(名称)',
            field: 'stockCode',
            filterType: 'search',
            filterField: 'codeOrName',
            notShowTooltip: true,
            filters: [{ data: '' }],
            // render: (value, row) => (value ? value + '(' + row.stockNameSt + ')' : '无'),
        },
        {
            title: '触警状态',
            field: 'thresholdType',
            width: '100',
        },
    ];
    pagingEntryDetail: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    // 颜色字典
    private ThresholadEntryColor = {
        '0': '#8bd197',
        '1': '#ff962c',
        '2': '#1d80ff',
        '3': '#df3a39',
        '4': '#6d5d5b',
    };
    filterParams: any = {};
    filterParamsEntryDetail: any = {
        codeOrName: '',
    };
    currentEntryInfo: any = {};
    tableKey: number = 0; // 用于重置表头条件
    mounted() {
        this.getTableDataEntry();
    }

    getTableDataEntry(seatchBtn: boolean = false) {
        let params = JSON.parse(JSON.stringify((this.$refs as any)['risk-search'].searchParams));
        // 过滤-1
        params.moduleList = params.moduleList.filter(i => i !== '-1');

        getEntryResult({ ...params, ...this.filterParams, paging: this.pagingEntry }).then((res: any) => {
            this.tableDataEntry = res.list;
            this.pagingEntry.total = res.total;
            seatchBtn && this.yh_message_success('查询成功');
        });
    }

    /**
     * 查看明细
     */
    openEntryResultDetail(row: any) {
        let currentEntryInfo = {
            entryCode: row.entryCode,
            fundCodes: [row.fundCode],
            row: JSON.parse(JSON.stringify(row)),
        };
        this.dispatch('ItemRealTimeMonitoring', 'handleEntryDetail', currentEntryInfo);
    }

    /**
     * 按钮点击
     */
    async handleBtn(type: string) {
        if (type == 'search') {
            this.pagingEntry.currentPage = 1;
            this.getTableDataEntry(true);
            this.pagingEntryDetail.currentPage = 1;
            this.pagingEntryDetail.total = 0;
            this.tableDataEntryDetail = [];
        } else if (type == 'reset') {
            this.tableKey++;
            this.filterParams = {};
            this.filterParamsEntryDetail.fundCode = '';
            this.filterParamsEntryDetail.fundNameSt = '';
            this.filterParamsEntryDetail.codeOrName = '';
            this.handleBtn('search');
        }
    }

    /**
     * 行点击
     */
    handleCellClick({ row }) {
        this.currentEntryInfo = JSON.parse(JSON.stringify(row));
        this.getTableDataEntryDetail();
    }

    // 条目明细产品
    getTableDataEntryDetail() {
        queryDetail({
            entryCodes: [this.currentEntryInfo.entryCode],
            // fundCodes: this.currentEntryInfo.fundCodes,
            ...this.filterParamsEntryDetail,
            paging: this.pagingEntryDetail,
        }).then((res: any) => {
            this.tableDataEntryDetail = res.list || [];
            // this.tableDataEntryDetail.map(item => {
            //     let str = item.stockCode;
            //     if (str && str.trim()) {
            //         item.stockCode = str.split(',');
            //     } else {
            //         item.stockCode = [];
            //     }
            //     return item;
            // });
            this.pagingEntryDetail.total = res.total;
        });
    }

    /**
     *  获取对象长度
     */
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    handleRowClick(row) {
        const msg = {
            type: 'look-entry-details',
            path: `/lookEntryDetails?entryCode=${row.entryCode}`,
            title: `条目详情-${row.entryCode}`,
        };
        top.window.postMessage(msg, '*');
    }
    setStockCode(row) {
        if (row.stockInfos && row.stockInfos.length > 0) {
            let arr = []
            row.stockInfos.forEach(item => {
                arr.push(item.dictKey + '(' + item.dictKeyName + ')')
            })
            return arr.join(',')    
        } else {
            return '--'
        }
    }
}
</script>
<style lang="scss" scoped>
.content {
    height: 100%;
    background: #f2f3f5;

    .el-row {
        height: calc(100% - 70px) !important;
        display: flex;
        .report {
            background: #fff;
            display: inline-block;
            width: calc(50% - 10px);
            height: 100%;
            border-radius: 5px;
        }
    }
}

.text-hover {
    cursor: pointer;

    &:hover {
        color: var(--primary);
        text-decoration: var(--primary) solid underline;
    }
}
</style>

<style>
.el-popover {
    padding: 10px;
    max-height: 200px;
    overflow: auto;
    background: #333;
    color: #fff;
}
</style>
